package com.eling.elcms.system.service.impl;

import com.eling.elcms.core.AppContext;
import com.eling.elcms.core.security.filter.TokenBasedPreAuthFilter;
import com.eling.elcms.privilege.model.User;
import com.eling.elcms.system.model.ElcmsUser;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.security.authentication.event.AuthenticationSuccessEvent;
import org.springframework.security.core.AuthenticationException;
import org.springframework.stereotype.Component;

/**
 * 登陆IP限制类，目的是为了比如让亲和源的秘书只能在社区里面使用系统，一方面是为了安全考虑， 另一方面是为了防止秘书在其他的地方签到
 * 
 * @author KEN
 *
 */
public class LoginIpRestrain {
	private static final Logger log = LoggerFactory.getLogger(LoginIpRestrain.class);

	@Component
	static class impl implements ApplicationListener<AuthenticationSuccessEvent> {
		@Override
		public void onApplicationEvent(AuthenticationSuccessEvent event) {
			// 预认证的登陆的用户不进行IP登录校验
			if (TokenBasedPreAuthFilter.isPreAuthenticated()) {
				return;
			}

			User user = (User) event.getAuthentication().getPrincipal();
			if (user instanceof ElcmsUser) {
				ElcmsUser eUser = (ElcmsUser) user;
				if (null == eUser.getCommunity()) {
					return;
				}
				String allowedIpStr = eUser.getCommunity().getPermissionIP();
				if (StringUtils.isBlank(allowedIpStr)) {
					return;
				}
				String[] allowedIps = allowedIpStr.split(";");
				if (Boolean.TRUE.equals(eUser.getCheckLoginIp())) {
					String clientIp = AppContext.getClientInfo().getIp();
					if (!ArrayUtils.contains(allowedIps, clientIp)) {
						log.info("IP登陆限制，当前IP为：{}，允许登陆IP为：{}", clientIp, allowedIpStr);
						throw new AuthenticationException("登陆限制，当前用户只允许在社区内登陆使用系统") {
							private static final long serialVersionUID = 1L;
						};
					}
				}
			}
		}

	}
}
